import 'package:flutter/material.dart';
import 'package:osc/common/MyTextStyle.dart';
import 'package:osc/common/osc_sp.dart';
import 'package:osc/data/repository/repository.dart';
import 'package:osc/models/entity/osc_topic_detail_entity.dart';
import 'package:osc/models/local_data/recent_topic_data.dart';
import 'package:osc/models/pop_result/pop_result.dart';
import 'package:osc/res/dimens.dart';
import 'package:osc/ui/widgets/common_scaffold.dart';
import 'package:osc/ui/widgets/small_widgets.dart';
import 'package:osc/utils/pd_util.dart';
import 'package:osc/utils/string_util.dart';

class TweetPickTopic extends StatefulWidget {
  @override
  _TweetPickTopicState createState() => _TweetPickTopicState();
}

class _TweetPickTopicState extends State<TweetPickTopic> {

  List<String> localTopics;

  List<OscTopicDetailEntity> topics;
  List<String> localRecommendList;


  TextEditingController textEditingController;
  FocusNode focusNode;
  String searchName;

  HttpRepository httpRepository;

  @override
  void initState() {
    super.initState();
    searchName = OscSp().getLastSearchName();
    textEditingController = TextEditingController();
    focusNode = FocusNode();
    localTopics = RecentTopicData().getRecentTopicList();
    localRecommendList = RecentTopicData().getRecommendList();
    topics = List();
    if(localRecommendList != null && localRecommendList.isNotEmpty){
      for(String title in localRecommendList){
        OscTopicDetailEntity entity = OscTopicDetailEntity(title: title);
        topics.add(entity);
      }
    }

    httpRepository = HttpRepository();
    getRecommendTopics();
  }
  @override
  void dispose() {
    super.dispose();
    textEditingController.dispose();
    focusNode.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return CommonScaffold(
        title: "选择话题",
        actions: <Widget>[
          SmallWidgets.buildAction(
              data: "确定",
              onTap: (){
                if(StringUtil.isEmpty(searchName)){
                  PdUtil.showToast(msg: "话题不能为空");
                } else {
                  Navigator.pop(context);
                }
              },
          ),
        ],
        body: buildBody(),
    );
  }

  buildBody(){
    return ListView(
      children: <Widget>[
        buildSearch(),
        buildLastInput(),
        buildRecommendTab(),
        buildRecommendTopics(),
        buildLocalTab(),
        buildLocalTopics(),
      ],
    );
  }

  buildSearch(){
    return Container(
      padding: EdgeInsets.symmetric(horizontal: Dimens.gap_view_normal),
      margin: EdgeInsets.all(Dimens.gap_view_normal),
      decoration: BoxDecoration(
        color: Colors.white70,
        border: Border.all(color: Colors.black12),
      ),
      child: Row(
        children: <Widget>[
          Image.asset(PdUtil.getImagePath("ic_tweet_topic_normal"), width: Dimens.view_item_icon_height_small, fit: BoxFit.contain,),
          Expanded(
            child: TextField(
              controller: textEditingController,
              focusNode: focusNode,
              style: MyTextStyle.QUESTION_INPUT_CONTENT,
              decoration: InputDecoration(
                hintText: "请输入话题或点击下列话题",
                hintStyle: MyTextStyle.QUESTION_INPUT_CONTENT_HINT,
                border: InputBorder.none,
                enabledBorder: InputBorder.none,
                focusedBorder: InputBorder.none,
                errorBorder: InputBorder.none,
                focusedErrorBorder: InputBorder.none,
                disabledBorder: InputBorder.none,
              ),
              textInputAction: TextInputAction.search,
              onChanged: (text){
                if(!StringUtil.isEmpty(text)){
                  searchName = text;
                  refreshView();
                }
              },
              onSubmitted: (text){

              },
            ),
          ),
        ],
      ),
    );
  }

  buildLastInput(){
    return GestureDetector(
      onTap: (){
        if(!StringUtil.isEmpty(searchName)){
          popResult(searchName);
        }
      },
      child: Container(
        alignment: Alignment.centerLeft,
        height: Dimens.view_item_height_biggest,
        color: Colors.white,
        padding: EdgeInsets.symmetric(horizontal: Dimens.gap_activity_horizontal),
        child: Text(StringUtil.isEmpty(searchName)? "" : "#$searchName"),
      ),
    );
  }

  buildTab(String data, bool offstage){
    return Offstage(
      offstage: offstage,
      child: Padding(
        padding: EdgeInsets.symmetric(horizontal: Dimens.gap_activity_horizontal, vertical: Dimens.gap_view_small),
        child: Text(data, style: MyTextStyle.LIST_BODY,),
      ),
    );
  }

  buildLocalTab(){
    return buildTab("本地保存话题", localTopics.length == 0);
  }

  buildRecommendTab(){
    return buildTab("热门话题", topics.length == 0);
  }

  buildLocalTopics(){
    return ListView.separated(
        shrinkWrap: true,
        primary: false,
        itemBuilder: (BuildContext context, int index){
          return buildTopicItem(localTopics.elementAt(index));
        },
        separatorBuilder: (BuildContext context, int index){
          return SmallWidgets.buildLine();
        },
        itemCount: localTopics.length,
    );
  }

  buildRecommendTopics(){
    return ListView.separated(
      shrinkWrap: true,
      primary: false,
      itemBuilder: (BuildContext context, int index){
        return buildTopicItem(topics.elementAt(index).title);
      },
      separatorBuilder: (BuildContext context, int index){
        return SmallWidgets.buildLine();
      },
      itemCount: topics.length,
    );
  }

  buildTopicItem(String title){
    return GestureDetector(
      onTap: (){
        popResult(title);
      },
      child: Container(
        alignment: Alignment.centerLeft,
        color: Colors.white,
        height: Dimens.view_item_height_normal,
        padding: EdgeInsets.symmetric(horizontal: Dimens.gap_activity_horizontal),
        child: Text(title, style: MyTextStyle.USER_LIST_TITLE,),
      ),
    );
  }


  popResult(String title){
    if(!StringUtil.isEmpty(title)){
      addRecentTopic(title);
      PopResult result = PopResult(id: PopResult.ID_PICK_TOPIC, success: true, extract: {"topic": title});
      Navigator.pop(context, result);
    }
  }

  addRecentTopic(String title){
    RecentTopicData().addRecentTopic(title: title);
  }

  refreshView(){
    if(mounted){
      setState(() {

      });
    }
  }

  getRecommendTopics() async{
    await httpRepository.getRecommendTopicList().then((resp){
      if(resp != null && resp.success){
        topics = resp.listResult;
        if(topics != null && topics.isNotEmpty) {
          localRecommendList.clear();
          for(OscTopicDetailEntity entity in topics){
            localRecommendList.add(entity.title);
          }
          RecentTopicData().setRecommendList(localRecommendList);
        }
        refreshView();
      }
    });
  }
}
